package com.zhucai.credit.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import org.jxls.common.Context;
import org.jxls.expression.JexlExpressionEvaluator;
import org.jxls.transform.Transformer;
import org.jxls.transform.poi.PoiTransformer;
import org.jxls.util.JxlsHelper;

public class JxlsUtils {
	private static void exportExcel(InputStream is, OutputStream os, Map<String, Object> model) throws IOException {

		Context context = PoiTransformer.createInitialContext();
		if (model != null) {
			for (String key : model.keySet()) {
				context.putVar(key, model.get(key));
			}
		}
		JxlsHelper jxlsHelper = JxlsHelper.getInstance();
		Transformer transformer = jxlsHelper.createTransformer(is, os);
		// 获得配置
		JexlExpressionEvaluator evaluator = (JexlExpressionEvaluator) transformer.getTransformationConfig()
				.getExpressionEvaluator();
		// 设置静默模式
		// evaluator.getJexlEngine().setSilent(true);
		// 函数强制
		Map<String, Object> funcs = new HashMap<String, Object>();
		funcs.put("utils", new JxlsUtils()); // 添加自定义功能
		evaluator.getJexlEngine().setFunctions(funcs);
		// 必须要这个，否者表格函数统计会错乱
		jxlsHelper.setUseFastFormulaProcessor(false).processTemplate(context, transformer);
	}

	public static void exportExcel(InputStream is, File out, Map<String, Object> model)
			throws IOException {
		
		if(!out.getParentFile().exists()) {
			out.getParentFile().mkdirs();
		}
		try (OutputStream os = new FileOutputStream(out)) {
			exportExcel(is, os, model);
		}
	}
	
	public static void exportExcel(File template, File out, Map<String, Object> model)
			throws FileNotFoundException, IOException {
		
		if(!out.getParentFile().exists()) {
			out.getParentFile().mkdirs();
		}
		try (InputStream is = new FileInputStream(template);OutputStream os = new FileOutputStream(out)) {
			if (template != null && template.exists()) {
				exportExcel(is, os, model);
			} else {
				throw new RuntimeException("Excel 模板未找到。");
			}
		}
	}

}
